﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Reflection;
using Pixysoft.Weblications.Sango.Formular;
using Pixysoft.Weblications.Sango.Dao;
using Pixysoft.Weblications.Sango.Protocol.player;
using Pixysoft.Weblications.Sango.Protocol;
using Pixysoft.Weblications.Sango.Environment;
using Pixysoft.Weblications.Sango.Constant;

namespace Pixysoft.Weblications.Sango.Command.section
{
    partial class SangoSectionHandler
    {
        public section_tradeapply section_tradeapply(long sectionserialcode, string targetusercode)
        {
            string usercode = SangoManager.Authentication();
            section_tradeapply response = ReflectionManager.CreatePojo<section_tradeapply>();
            response.Succeed = false;

            Entities.Usr_Profile myprofile = UsrProfileDao.getUsrProfile(usercode);
            Entities.Usr_Activity myactivity = UsrActivityDao.getHistory(usercode);
            Entities.Usr_Profile targetprofile = UsrProfileDao.getUsrProfile(targetusercode);
            Entities.Cti_Section section = CitySectionHelper.searchSectionByCode(sectionserialcode);

            if (myactivity.Tradecount + 1 > SectionFormular.default_trade_count)
            {
                response.Message = "每日通商次数达到上限。";
                return response;
            }

            Entities.Usr_Building building = UsrBuildingDao.getUserBuilding(usercode, CtiBuildingTypecodeCollection.TRADE);
            long tocash = SectionFormular.getTradeToCash(section, targetprofile, building.Buildinglevel);
            UsrProfileDao.increaseCashvalueToMax(myprofile, tocash);

            long bonuscash = SectionFormular.getTradeBonusCash(section, targetprofile, building.Buildinglevel);
            UsrProfileDao.increaseCashvalueToMax(targetprofile, bonuscash);

            Entities.Usr_Mission mission = MissionDao.getMission(usercode);

            IEntityNoebeTransaction command = SettingHelper.EntityTransaction;

            command.Begin(delegate()
            {
                myactivity.Tradecount = myactivity.Tradecount + 1;
                command.Update(myactivity);

                command.Update(myprofile);

                command.Update(targetprofile);

                if (MissionDao.processDailyMission(mission, MissionDailyCollection.TRADE))
                {
                    command.Update(mission);
                }

                command.Commit();
            });

            response.profile = UsrProfileFacade.ToProfile(myprofile);
            response.Succeed = true;
            return response;
        }
    }

    public interface section_tradeapply : ISangoResponse
    {
        player_profile profile { get;set;}
    }
}
